package com.library.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.library.bean.Book;
import com.library.service.BookService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

@Controller
public class BookController {

    @Resource
    private BookService bookService;

    @GetMapping("/books")
    @ResponseBody
    public Object getAllBooks(Book book,
                              @RequestParam(required = false,defaultValue = "1") int pageNum,
                              @RequestParam(required = false,defaultValue = "10") int pageSize){

        // 启用分页功能，设置当前页和每页大小
        PageHelper.startPage(pageNum,pageSize);

        // 根据条件筛选书籍，并执行分页查询
        Page<Book> page = (Page<Book>)bookService.selectBooksByCondition(book);

        // 将分页查询结果转换为PageInfo对象并返回
        return page.toPageInfo();
    }

    @RequestMapping("/deleteBook")
    @ResponseBody
    public String deleteBook(int id) {
        int result = bookService.deleteBook(id);
        return result == 1 ? "success" : "fail";
    }

    @RequestMapping("/book")
    public String updateBook(Book book) {
        bookService.updateBook(book);
        return "redirect:/books.jsp";
    }

    @PostMapping("/addBook")
    public String addBook(Book book, Model model) {
        if (bookService.insertBook(book)==-1) {
            model.addAttribute("msg", "书名已存在");
            return "forward:addBook.jsp";
        }
        return "redirect:/books.jsp";
    }


}
